/* global L */
class Draw {
  constructor() {
    //绘制的坐标
    this.geom = null
    //绘制的图层
    this.polygon = null
    this.drawClick = true
    this.geoJson = null
  }
  //多边形绘画
  DrawPolygon() {
    this.clearDraw()
    var ls
    var points = []
    var lines = new L.polyline([])
    var tempLines = new L.polygon([])
    L.DomUtil.addClass(window.map._container, 'leaflet-cursor-crosshair')
    //点击地图确定多变形的顶点
    window.map.on('click', clickPolygon, this)
    function clickPolygon(e) {
      points.push([e.latlng.lat, e.latlng.lng])
      lines.addLatLng(e.latlng)
      window.map.addLayer(lines)
    }
    //双击地图结束绘制
    window.map.on('dblclick', () => {
      points[points.length - 1] = points[0]
      this.geom = points
      window.map.removeLayer(lines)
      window.map.removeLayer(tempLines)
      this.polygon = L.polygon([points], {
        color: 'red',
        fillColor: 'rgb(123,180,255)',
        fillOpacity: 0.5,
      }).addTo(window.map)
      // console.log(this.polygon, this.geom)
      var geoJs = { type: 'Polygon', coordinates: [points] }
      var geoJ = L.geoJSON(geoJs)
      // eslint-disable-next-line no-undef
      var pgeo = L.Util.transform(geoJ, L.CRS.EPSG4326, GZ2000)
      this.geoJson = pgeo.features[0].geometry
      points = []
      lines = new L.polyline([])
      window.map.off('dblclick')
      window.map.off('click', clickPolygon, this)
      window.map.off('mousemove', this)
      this.drawClick = true
      L.DomUtil.removeClass(window.map._container, 'leaflet-cursor-crosshair')
      this.type = ''
    })
    //移动鼠标确定顶点间的距离
    window.map.on(
      'mousemove',
      (e) => {
        if (points.length > 0) {
          ls = [points[points.length - 1], [e.latlng.lat, e.latlng.lng]]
          tempLines.setLatLngs(ls)
          window.map.addLayer(tempLines)
        }
      },
      this,
    )
  }

  //清除绘制的polygon
  clearDraw() {
    if (this.polygon != null) {
      window.map.removeLayer(this.polygon)
    }
    this.geoJson = null
  }
}

export { Draw }
